# @time     :2022/1/20
# @Author   :Simple
# @FileName :handle_black_list
import os

from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver

from config import IMAGE_REPORT
from util.logger import log as logger


def get_screenshots(driver: WebDriver, file_name):
    """
    截图
    :param driver:
    :param file_name: 截图文件名
    :return:
    """
    image_dir = os.path.join(IMAGE_REPORT, file_name)
    logger.info(f"截图路径:{image_dir}")
    driver.save_screenshot(image_dir)


def handle_black(func):
    """
    处理黑名单节点的装饰器，未找到元素时截图
    :param func:
    :return:
    """

    def run(*args, **kwargs):
        # 使用装饰器
        black_list = ['//*[@resource-id="com.xueqiu.android:id/iv_close"]']
        instance = args[0]
        try:
            return func(*args, **kwargs)
        except Exception:
            if len(args) > 1:
                element = args[0]
                driver: WebDriver = args[1]
                file_name = "未找到元素(" + element.describe + ")的截图.png"
                image_dir = os.path.join(IMAGE_REPORT, file_name)
                logger.warning(f"元素未找到→{element.locator}，开始截图：{image_dir}")
                driver.save_screenshot(image_dir)
            for ele_xpath in black_list:
                eles = instance.driver.find_elements(MobileBy.XPATH, ele_xpath)
                # 查找黑名单中的节点，出现后处理掉
                if len(eles) > 0:
                    eles[0].click()
                    # 再次查找需要的节点，若不出现，则循环处理黑名单节点
                    return func(*args, **kwargs)

    return run

